package com.hr.mes.config;

import com.hr.mes.dto.JWTToken;
import com.hr.mes.service.impl.PermissionCacheService;
import com.hr.mes.utils.JWTUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

public class JWTRealm extends AuthorizingRealm {

    @Autowired
    private PermissionCacheService permissionCacheService;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 是自定义的JWTToken才执行认证或授权
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String employeeNumber = (String) principalCollection.getPrimaryPrincipal();
        //如果shiro:permissionList中已存在key=employeeNumber的缓存，则返回其value，否则从数据库查询权限列表，写入缓存并返回
        Cache cache = cacheManager.getCache("shiro:permissionList");
        Cache.ValueWrapper valueWrapper = cache.get(employeeNumber);
        if(!ObjectUtils.isEmpty(valueWrapper)) {
            Object value = valueWrapper.get();
            if (value instanceof SimpleAuthorizationInfo) {
                return (SimpleAuthorizationInfo) value;
            }
        }
        SimpleAuthorizationInfo info = permissionCacheService.getAuthorizationInfoFromCache(employeeNumber);
        cache.put(employeeNumber, info);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JWTToken jwt = (JWTToken) authenticationToken;
        String token = (String)jwt.getCredentials();
        try{
            JWTUtil.verify(token);
            return new SimpleAuthenticationInfo(jwt.getPrincipal(), token, getName());
        }catch (ExpiredJwtException e){
            throw new AuthenticationException("token已过期", e);
        }catch (JwtException e) {
            throw new AuthenticationException("无效的token", e);
        }
    }

}
